import useForceUpdate from 'use-force-update';
import toml from "@iarna/toml";
import { useState } from 'react';
import { Button, Card, Space, Tabs } from 'antd';
import { min_app_fs, min_app_shell } from '@linksaas-minapp/api';
import { ParamGroupList } from '@/components/params';
import { RuffConfig, ToolRuffConfig } from '@/components/config';
import { ParamPanel } from '@/components/ParamPanel';

export default function Home() {
  const forceUpdate = useForceUpdate();

  const [ruffCfg, setRuffCfg] = useState<RuffConfig>({});

  const openFile = async () => {
    let files = await min_app_fs.readFile(
      false,
      "toml文件", ["toml"]
    );
    if (files.length == 0) {
      return;
    }
    try {
      const content = new TextDecoder("utf-8").decode(files[0].file_data);
      const cfg = toml.parse(content);
      setRuffCfg(cfg);
      forceUpdate();
    } catch (e) {
      console.log(e);
    }
  };

  const saveFile = async () => {
    const content = toml.stringify(ruffCfg as unknown as toml.JsonMap);
    const data = new TextEncoder().encode(content);
    await min_app_fs.writeFile("ruff.toml", data);
  };

  const getCfgvalue = (pg: string) => {
    if (pg == "") {
      return ruffCfg.tool?.ruff ?? {};
    } else {
      if (ruffCfg.tool?.ruff == undefined) {
        return {};
      } else {
        return ruffCfg.tool.ruff[pg] ?? {};
      }
    }
  }

  return (
    <Card title="ruff配置" bordered={false} extra={
      <Space>
        <Button type="link" onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          min_app_shell.openBrowser("https://beta.ruff.rs/docs/");
        }}>官方网站</Button>
        <Button onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          setRuffCfg({});
          forceUpdate();
        }}>清空配置</Button>
        <Button onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          openFile();
        }}>导入</Button>
        <Button onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          saveFile();
        }}>导出</Button>
      </Space>
    }>
      <Tabs defaultActiveKey=''>
        {ParamGroupList.map(pg => (
          <Tabs.TabPane key={pg.groupName} tab={pg.groupName == "" ? "全局" : pg.groupName}>
            <ParamPanel params={pg.paramList} cfg={getCfgvalue(pg.groupName)} onChange={newValue => {
              let tmpCfg = ruffCfg;
              if (tmpCfg.tool == undefined) {
                tmpCfg.tool = {};
              }
              if (tmpCfg.tool.ruff == undefined) {
                tmpCfg.tool.ruff = {};
              }
              if (pg.groupName == "") {
                tmpCfg.tool.ruff = newValue as ToolRuffConfig;
              } else {
                tmpCfg.tool.ruff[pg.groupName] = newValue;
              }
              forceUpdate();
            }} />
          </Tabs.TabPane>
        ))}
      </Tabs>
    </Card >
  )
}
